import fs from 'fs';
import path from 'path';
import Jimp from 'jimp';
import { connection } from '../app/database/mysql';
import { goldPostsModel } from './goldPosts.model';
import { APP_URL, STATIC_PATH } from '../app/app.config';
import { cornerStatusChangeByType, saveCorner } from '../corner/common.service';
import { IMAGE_TYPE_GOLD } from '../app/constants';

/**
 * 获取内容
 */
export const getGoldPosts = async (status: number, pageSize: number, pageNo: number, userId: number) => {
  // 准备查询
  let statement = `
    SELECT SQL_CALC_FOUND_ROWS * FROM gold_posts
  `;
  let where = []
  if (status >= 0) {
    where.push(`status = ` + status)
  }
  if (userId > 0) {
    where.push(`user_id = ` + userId)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }
  statement += ` ORDER by id DESC limit ` + (pageNo > 0 ? (pageNo - 1) * pageSize : 0) + `,` + pageSize


  // 执行查询
  const [data] = await connection.promise().query(statement)

  let totalStatement = `SELECT FOUND_ROWS() as total`
  const [result] = await connection.promise().query(totalStatement)
  let totalCount = result[0].total
  let totalPage = (totalCount % pageSize) > 0 ? parseInt(`${totalCount / pageSize}`) + 1 : totalCount / pageSize

  for (let item of data as any) {
    let cover = await findFileById(item.image_id, 0, 0, 'thumbnail')
    item.cover = cover[0];
  }
  let res = {
    data,
    totalPage,
    totalCount
  }

  return res;
};

/**
 * 获取产品
 */
export const getGoldProduct = async (status: number,type:number, shop_id: number, pageSize: number, pageNo: number, userId: number) => {
  // 准备查询
  let statement = `
    SELECT SQL_CALC_FOUND_ROWS  * FROM gold_product
  `;
  let where = []
  if (status >= 0) {
    where.push(`status = ` + status)
  }
  if (shop_id >= 0) {
    where.push(`shop_id = ` + shop_id)
  }
  if (type >= 0) {
    where.push(`type = ` + type)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }
  statement += ` ORDER by sortNum DESC, id DESC limit ` + (pageNo > 0 ? (pageNo - 1) * pageSize : 0) + `,` + pageSize
  
  // 执行查询
  const [data] = await connection.promise().query(statement)

  let totalStatement = `SELECT FOUND_ROWS() as total`
  const [result] = await connection.promise().query(totalStatement)
  let totalCount = result[0].total
  let totalPage = (totalCount % pageSize) > 0 ? parseInt(`${totalCount / pageSize}`) + 1 : totalCount / pageSize

  // 今日黄金价格
  let processing_fee = `SELECT price FROM gold_posts order by id DESC LIMIT 1`
  const [result_1] = await connection.promise().query(processing_fee)
  let result_price = result_1[0].price

  for (let item of data as any) {
    let cover = await findFileById(item.image_id, 0, 0, 'thumbnail')
    item.cover = cover[0];
    let images = await findFileById(0, item.id, IMAGE_TYPE_GOLD, 'thumbnail')
    item.images = images;
    let price = await (result_price + item.processing_fee) * item.weight
    item.price = price.toFixed(2)
  }
  let res = {
    data,
    totalPage,
    totalCount
  }
  // 提供数据
  return res;
};

/**
 * 按 ID 获取内容
 */
export const getIdGoldPosts = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM gold_posts
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data[0];
}

/**
 * 按 ID 获取产品
 */
export const getIdGoldProduct = async (postId: number, type: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM gold_product
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);
  let goldProduct = data[0] as any
  if (goldProduct) {
    let images = await findFileById(0, goldProduct.id, 1, 'thumbnail');
    goldProduct.images = images;
  }

  // 提供数据
  return goldProduct;
}

/**
 * 创建内容
 */
export const createGoldPosts = async (post: goldPostsModel) => {
  // 准备查询
  const statement = `
    INSERT INTO gold_posts
    SET ?
  `;
  
  // 执行查询
  const [data] = await connection.promise().query(statement, post);
  
  // 提供数据
  return data;
};

/**
 * 创建产品
 */
export const createGoldProduct = async (post: goldPostsModel) => {
  // 准备查询
  const statement = `
    INSERT INTO gold_product
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);
  
  if ((data as any).insertId > 0) {
    await saveCorner((data as any).insertId, 1, parseInt(`${post.user_id}`, 10), 0)
  }
  
  // 提供数据
  return data;
};

/**
 * 更新内容
 */
export const updateGoldPosts = async (post: goldPostsModel, postId: number) => {
  // 准备查询
  const statement = `
    UPDATE gold_posts
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
}

/**
 * 更新产品
 */
export const updateGoldProduct = async (post: goldPostsModel, postId: number) => {
  // 准备查询
  const statement = `
    UPDATE gold_product
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
}

/**
 * 删除内容
 */
export const deleteGoldPosts = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM gold_posts
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}

/**
 * 删除产品
 */
export const deleteGoldProduct = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM gold_product
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}

/**
 * 状态
 */
export const goldPostsStatusChange = async (postId: number, post: any) => {
  // 准备数据
  const statement = `
    UPDATE gold_product
      SET ?
      WHERE id = ?
  `;
  
  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);
  
  // 提供数据
  return data;
};

/**
 * 存储文件信息
 */
export const createFile = async (
  file: goldPostsModel
) => {
  // 准备查询
  const statement = `
    INSERT INTO resource
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, file);

  // 提供数据
  return data;
}

/**
 * 更新文件信息
 */
export const updateFile = async (post: goldPostsModel, postId: number) => {
  const statement = `
    UPDATE resource
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
}

/**
 * 按 ID 查找文件
 */
export const findFileById = async (fileId: number, targetId: number, type: number, ...size: any) => {
  // 准备查询
  let sql = 'SELECT * FROM resource ';
  let and = false;
  if (fileId > 0) {
    sql += " where id = " + fileId;
    and = true;
  }
  if (targetId > 0) {
    sql += (and ? " and " : " where ") + " target_id = " + targetId;
    and = true;
  }
  if (type > 0) {
    sql += (and ? " and " : " where ") + " target_type = " + type;
  }

  // 执行查询
  const [data] = await connection.promise().query(sql);
  for (let item of data as any) {
    if (size && size.length > 0) {
      item.fullUrl = APP_URL + item.url + '/resized/' + item.filename + "-" + size[0]
    } else {
      item.fullUrl = APP_URL + item.url + item.filename
    }
  }
  // 提供数据
  return data as any;
}

/**
 * 删除内容文件
 */
export const deleteFileById = async (file: goldPostsModel) => {
  if (!file.id || file.id <= 0) return
  const statement = `delete from resource where id = ?`;
  const [data] = await connection.promise().query(statement, file.id);
  if ((data as any).affectedRows > 0) {
    let path = STATIC_PATH + file.url + file.filename

    try {
      fs.unlinkSync(path);
    } catch (error) {
      console.log("fileDeleteErr:", error);
    }
  };

}

/**
 * 调整图像尺寸
 */
export const imageResizer = async (
  image: Jimp,
  file: Express.Multer.File
) => {
  Jimp.loadFont(Jimp.FONT_SANS_64_WHITE).then(font => {
    image.print(font, 10, 10, 'VIPAtush');

    // 图像尺寸
    const { imageSize } = image['_exif'];

    // 文件路径
    const filePath = path.join(file.destination, 'resized/', file.filename);

    // 大尺寸
    if (imageSize.width > 1080) {
      image
        .resize(1080, Jimp.AUTO)
        .quality(85)
        .write(`${filePath}-lerge`);
    }

    // 中等尺寸
    if (imageSize.width > 440) {
      image
        .resize(440, Jimp.AUTO)
        .quality(95)
        .write(`${filePath}-medium`);
    }

    // 缩略图
    if (imageSize.width > 320) {
      image
        .resize(320, Jimp.AUTO)
        .quality(85)
        .write(`${filePath}-thumbnail`);
    }
  })
}
